package com.toman.Login;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.device.DeviceManager;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.nfc.tech.NfcF;
import android.nfc.tech.NfcV;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.toman.Adpter.ItemListAdapter;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.SysUserEntity;
import com.toman.MyApplication;
import com.toman.R;
import com.toman.Util.IntentUtils;
import com.toman.Util.JsonUtils;
import com.toman.Util.NetworkUtils;
import com.toman.Util.SPUtils;
import com.toman.Util.StringUtils;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.bean.ItemListBean;
import com.toman.ui.HomeActivity;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.leefeng.promptlibrary.PromptDialog;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;
public class LoginActivity extends AppCompatActivity {

    protected NfcAdapter nfcAdapter;
    protected PendingIntent pendingIntent;
    @BindView(R.id.iv_title)
    ImageView ivTitle;
    @BindView(R.id.et_account)
    EditText etAccount;
    @BindView(R.id.et_pwd)
    EditText etPwd;
    @BindView(R.id.LL_edit)
    LinearLayout LLEdit;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.tv_forget)
    TextView tvForget;
    MyApplication myApplication;
    PromptDialog promptDialog;
    List<ItemListBean> list = new ArrayList<ItemListBean>();
    ItemListAdapter adapter;
    DeviceManager mDevice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 隐藏标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //一定要放在setContentView()之前！

        setContentView(R.layout.activity_login2);
        ButterKnife.bind(this);
        initView();
        initNFC();

        PushAgent.getInstance(this).onAppStart();
//        initPermmison();
    }

    private void initNFC() {
        try {
            nfcAdapter = NfcAdapter.getDefaultAdapter(this);
            pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
                    getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
            // 检查nfc是否开启
            checkNfc();
            onNewIntent(getIntent());
        } catch (Exception e) {
            e.printStackTrace();
            isLogin();
        }
    }

    private void initView() {
        myApplication = (MyApplication) getApplication();
        promptDialog = new PromptDialog(this);
        etAccount.setText((String) SPUtils.get(getApplicationContext(), "phone", ""));
        adapter = new ItemListAdapter(this);
        if (getIntent().getBooleanExtra("change",false)){
                    etPwd.setText((String) SPUtils.get(getApplicationContext(), "pwd", ""));
login();
        }
//        etPwd.setText((String) SPUtils.get(getApplicationContext(), "pwd", ""));

    }

    @OnClick({R.id.btn_login, R.id.tv_forget})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                login();
                break;
            case R.id.tv_forget:
                etAccount.setText("18967092210");
                etPwd.setText("123456");
                login();
//                IntentUtils.startActivity(this,InputPhoneActivity.class);
                break;
        }
    }

    private void login() {

        if (!NetworkUtils.checkNetState(getApplicationContext())) {
            ToastUtil.makeText(this, R.string.net_error);
            return;
        }
//        if (etAccount.getText().toString().equals("1")) {
//            IntentUtils.startActivity(this, HomeActivity.class);
//
//            SPUtils.put(getApplicationContext(), "is_login", true);
//        }
        if (etAccount.getText().toString().length() < 11) {
            ToastUtil.makeText(this, "请输入正确的手机号");
            return;
        }
        if (etPwd.getText().toString().length() < 6) {
            ToastUtil.makeText(this, "请输入正确的密码");
            return;
        }
        promptDialog.showLoading("正在登录");
        String model = android.os.Build.MODEL;
        String brand = android.os.Build.BRAND;
        String msg = model + brand;

        Map<String, String> map = new HashMap<String, String>();
        map.put("mobile", etAccount.getText().toString());
        map.put("password", etPwd.getText().toString());
        map.put("mobile_model", msg);
        String str = JsonUtils.obj2JsonString(map);
        OkHttpUtils
                .post(NewBaseUrl.Login_post)
//                .params("username", etAccount.getText().toString())
//                .params("password", etPwd.getText().toString())
                .postJson(str)
                .execute(new StringCallback() {

                             @Override
                             public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                                 super.onError(isFromCache, call, response, e);
//                                 Toast.makeText(getApplicationContext(), "请检查您的网络连接!", Toast.LENGTH_SHORT).show();
                                 promptDialog.showWarn("请检查您的网络连接");

                             }

                             @Override
                             public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                                 Log.i("test", "登录: " + result);
                                 JSONObject jsonObj = JSON.parseObject(result);
                                 int code = jsonObj.getInteger("code");
                                 ViewUtil.lagout(code,getApplicationContext());


                                 if (code == 0) {
                                     SysUserEntity bean = (SysUserEntity) JSON.parseObject(jsonObj.getString("sysUserEntity"), SysUserEntity.class);
                                     SPUtils.put(getApplicationContext(), "cpy_id", bean.getCompanyId());
                                     SPUtils.put(getApplicationContext(), "token", jsonObj.getString("token"));
                                     SPUtils.put(getApplicationContext(), "username", bean.getRealName());
                                     SPUtils.put(getApplicationContext(), "userid", bean.getUserId());
                                     SPUtils.put(getApplicationContext(), "departmentId", bean.getDepartmentId());
                                     try {
                                         SPUtils.put(getApplicationContext(), "departmentName", bean.getDepartmentName());
                                     } catch (Exception e) {
                                         e.printStackTrace();
                                     }
                                     SPUtils.put(getApplicationContext(), "phone", etAccount.getText().toString());
                                     SPUtils.put(getApplicationContext(), "pwd", etPwd.getText().toString());
                                     MyApplication.getInstance().setMCompanyId(bean.getCompanyId());
                                     MyApplication.getInstance().setToken(jsonObj.getString("token"));
                                     MyApplication.getInstance().setUsername(bean.getRealName());
                                     MyApplication.getInstance().setUserId(bean.getUserId());
                                     MyApplication.getInstance().setDepartmentId(bean.getDepartmentId());


//                                     success(bean);
                                     try {
                                         JSONArray jsonArray = jsonObj.getJSONArray("multipleCompanyList");
                                         if (jsonArray.size()<=1){
                                             success(bean);
                                         }
                                      else {   list.clear();
                                             promptDialog.dismiss();

                                             for (int i = 0; i < jsonArray.size(); i++) {
                                             ItemListBean companyBean = new ItemListBean(jsonArray.getJSONObject(i).getString("name"), jsonArray.getJSONObject(i).getString("companyId"));
                                             list.add(companyBean);
                                         }
                                         companyDialog(bean);

                                        }
                                     } catch (Exception e) {
                                         e.printStackTrace();
                                         success(bean);
                                     }
                                 } else {
                                     promptDialog.dismiss();

                                     ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));
                                 }

                             }

                             public void onError(Call call, Exception e) {

                                 ToastUtil.makeText(getApplicationContext(), "网络不稳定，请稍后再试");
                             }
                         }

                );


    }
    private void nfcLogin(String userRfid,String handheldSn) {

        if (!NetworkUtils.checkNetState(getApplicationContext())) {
            ToastUtil.makeText(this, R.string.net_error);
            return;
        }
//        if (etAccount.getText().toString().equals("1")) {
//            IntentUtils.startActivity(this, HomeActivity.class);
//
//            SPUtils.put(getApplicationContext(), "is_login", true);
//        }

        promptDialog.showLoading("正在登录");
        String model = android.os.Build.MODEL;
        String brand = android.os.Build.BRAND;
        String msg = model + brand;

        Map<String, String> map = new HashMap<String, String>();
        map.put("mobile", etAccount.getText().toString());
        map.put("password", etPwd.getText().toString());
        map.put("mobile_model", msg);
        String str = JsonUtils.obj2JsonString(map);
        OkHttpUtils
                .get(NewBaseUrl.pda_login)
                .params("userRfid", userRfid)
                .params("handheldSn", handheldSn)
//                .postJson(str)
                .execute(new StringCallback() {

                             @Override
                             public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                                 super.onError(isFromCache, call, response, e);
//                                 Toast.makeText(getApplicationContext(), "请检查您的网络连接!", Toast.LENGTH_SHORT).show();
                                 promptDialog.showWarn("请检查您的网络连接");

                             }

                             @Override
                             public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                                 Log.i("test", "登录: " + result);
                                 JSONObject jsonObj = JSON.parseObject(result);
                                 int code = jsonObj.getInteger("code");
//                                 ViewUtil.lagout(code,getApplicationContext());


                                 if (code == 0) {
                                     SysUserEntity bean = (SysUserEntity) JSON.parseObject(jsonObj.getString("sysUserEntity"), SysUserEntity.class);
                                     SPUtils.put(getApplicationContext(), "cpy_id", bean.getCompanyId());
                                     SPUtils.put(getApplicationContext(), "token", jsonObj.getString("token"));
                                     SPUtils.put(getApplicationContext(), "username", bean.getRealName());
                                     SPUtils.put(getApplicationContext(), "userid", bean.getUserId());
                                     SPUtils.put(getApplicationContext(), "departmentId", bean.getDepartmentId());
                                     try {
                                         SPUtils.put(getApplicationContext(), "departmentName", bean.getDepartmentName());
                                     } catch (Exception e) {
                                         e.printStackTrace();
                                     }
//                                     SPUtils.put(getApplicationContext(), "phone", etAccount.getText().toString());
//                                     SPUtils.put(getApplicationContext(), "pwd", etPwd.getText().toString());
                                     MyApplication.getInstance().setMCompanyId(bean.getCompanyId());
                                     MyApplication.getInstance().setToken(jsonObj.getString("token"));
                                     MyApplication.getInstance().setUsername(bean.getRealName());
                                     MyApplication.getInstance().setUserId(bean.getUserId());
                                     MyApplication.getInstance().setDepartmentId(bean.getDepartmentId());


//                                     success(bean);
                                     try {
                                         JSONArray jsonArray = jsonObj.getJSONArray("multipleCompanyList");
                                         if (jsonArray.size()<=1){
                                             success(bean);
                                         }
                                         else {   list.clear();
                                             promptDialog.dismiss();

                                             for (int i = 0; i < jsonArray.size(); i++) {
                                                 ItemListBean companyBean = new ItemListBean(jsonArray.getJSONObject(i).getString("name"), jsonArray.getJSONObject(i).getString("companyId"));
                                                 list.add(companyBean);
                                             }
                                             companyDialog(bean);

                                         }
                                     } catch (Exception e) {
                                         e.printStackTrace();
                                         success(bean);
                                     }
                                 } else {
                                     promptDialog.dismiss();

                                     ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));
                                 }

                             }

                             public void onError(Call call, Exception e) {

                                 ToastUtil.makeText(getApplicationContext(), "网络不稳定，请稍后再试");
                             }
                         }

                );


    }

    public void companyDialog(SysUserEntity sysUserEntity) {
        final AlertDialog dialog;
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater factory = LayoutInflater.from(this);
        //把activity_login中的控件定义在View中
        final View textEntryView = factory.inflate(R.layout.dialog_list, null);
        ListView lv = (ListView) textEntryView.findViewById(R.id.lv);
        lv.setAdapter(adapter);
        adapter.refreshData(list);

        builder                //对话框的标题
                .setTitle("选择登录企业")
                //设定显示的View
                .setView(textEntryView)
                //对话框中的“登陆”按钮的点击事件
                .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        //获取用户输入的“用户名”，“密码”


                    }
                })
                //对话框的“退出”单击事件
//                .setNegativeButton("退出", new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialog, int whichButton) {
//                    }
//                })
                // 设置dialog是否为模态，false表示模态，true表示非模态
                .setCancelable(true)
                //对话框的创建、显示
                .create();
        dialog = builder.show();

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ItemListBean bean = adapter.getItem(i);

                String companyId = bean.getID();
                SPUtils.put(getApplicationContext(), "cpy_id",companyId);
                SPUtils.put(getApplicationContext(), "muti_company",true);

                update(companyId);
                success(sysUserEntity);
                dialog.dismiss();
            }
        });

    }

    private void success(SysUserEntity bean) {
        myApplication.setMobile(etAccount.getText().toString());
        MobclickAgent.onProfileSignIn(bean.getUserId());
        promptDialog.showSuccess("登录成功");

        promptDialog.dismiss();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        PushAgent pushAgent = myApplication.mPushAgent;
        ToastUtil.print("device: " + SPUtils.get(getApplicationContext(), "deviceToken", ""));

        pushAgent.addAlias(bean.getUserId(), "toman", (b, s) -> {
            if (b) {
                ToastUtil.print("绑定成功" + s);
            } else {
                ToastUtil.print("绑定失败" + s);
            }
        });


        SPUtils.put(getApplicationContext(), "is_login", true);
        isLogin();
    }
    public void update(String companyId) {
        Map<String, String> map = new HashMap<String, String>();
map.put("companyId",companyId);


        String str = JsonUtils.obj2JsonString(map);
        ToastUtil.print("发送json" + str);
        OkHttpUtils
                .post(NewBaseUrl.user_update_post_user)
                .headers("token", (String) SPUtils.get(getApplicationContext(),"token",""))
                .postJson(str)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "编辑用户: " + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");
                        ViewUtil.lagout(code,getApplicationContext());

                        if (code == 0) {


                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }


    public void isLogin() {
        if ((boolean) SPUtils.get(getApplicationContext(), "is_login", false) == true) {
            IntentUtils.startActivity(this, HomeActivity.class);


        }
    }

    @SuppressLint("NewApi")
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        if (nfcAdapter != null)
            nfcAdapter.enableForegroundDispatch(this, pendingIntent, FILTERS,
                    TECHLISTS);

    }

    @SuppressLint("NewApi")
    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        if (nfcAdapter != null)
            nfcAdapter.disableForegroundDispatch(this);
    }

    @SuppressLint("NewApi")
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub
        super.onNewIntent(intent);
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {


        } else {
            if (tag != null) {

                // 获取卡类型，根据卡类型可推出卡协议
                String[] techList = tag.getTechList();
                StringBuffer techString = new StringBuffer();
                for (int i = 0; i < techList.length; i++) {
                    techString.append(techList[i]);
                    techString.append(";\n");
                }
                // 获取卡id
                byte[] id = tag.getId();
                mDevice = new DeviceManager();
                String sn="123";
                try {
                    sn=mDevice.getDeviceId();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                String refID=hex2Decimal(ByteArrayToHexString(id));
                ToastUtil.print("refid"+refID+"sn:"+sn);

if (StringUtils.isNotEmpty(refID)){
    nfcLogin(refID,sn);
}
                etAccount.setText(refID);
//
//                etPwd.setText(hex2Decimal(ByteArrayToHexString(id)));
                SPUtils.clear(this);


//                mifareClassic = MifareClassic.get(tag);
//                if (mifareClassic != null) {
//                    showView(1);
//                } else {
//                    showView(0);
//                }
            }
            else {
                isLogin();
            }

        }
    }


    @SuppressLint("NewApi")
    protected void checkNfc() {
        if (!nfcAdapter.isEnabled()) {
//            startActivity(new Intent(
//                    android.provider.Settings.ACTION_NFC_SETTINGS));
        }

        // // TODO Auto-generated catch block

    }
    public static String hex2Decimal(String hex) {
        StringBuilder builder = new StringBuilder();
        if(hex.length() == 8) {
            for(int i = 0; i<4; i++) {
                String str = hex.substring(hex.length()-2 * (i+1), hex.length()-2*i);
                builder.append(str);
            }
        }
        String decimal = String.valueOf(Long.parseLong(builder.toString(), 16));
        while (decimal.length() < 10) {
            decimal = "0" + decimal;
        }

        return decimal;
    }


    protected String ByteArrayToHexString(byte[] inarray) {
        int i, j, in;
        String[] hex = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A",
                "B", "C", "D", "E", "F" };
        String out = "";
        //反过来转换成10进制

        for (j = 0; j < inarray.length; ++j) {
            in = inarray[j] & 0xff;
            i = (in >> 4) & 0x0f;
            out += hex[i];
            i = in & 0x0f;
            out += hex[i];
        }
        return out;
    }

    public static String[][] TECHLISTS;
    @SuppressLint("NewApi")
    public static IntentFilter[] FILTERS;

    static {
        try {
            TECHLISTS = new String[][] { { IsoDep.class.getName() },
                    { NfcV.class.getName() }, { NfcF.class.getName() }, };

            FILTERS = new IntentFilter[] { new IntentFilter(
                    NfcAdapter.ACTION_TECH_DISCOVERED, "*/*") };
        } catch (Exception e) {
        }
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            //启动一个意图,回到桌面
            Intent backHome = new Intent(Intent.ACTION_MAIN);
            backHome.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            backHome.addCategory(Intent.CATEGORY_HOME);
            startActivity(backHome);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public static String getDeviceSN(){

        String serialNumber = android.os.Build.SERIAL;

        return serialNumber;
    }
    public static String getSerialNumber(){

        String serial = null;

        try {

            Class<?> c =Class.forName("android.os.SystemProperties");

            Method get =c.getMethod("get", String.class);

            serial = (String)get.invoke(c, "ro.serialno");

        } catch (Exception e) {

            e.printStackTrace();

        }

        return serial;

    }

}
